package com.yykj.im.center.server.repository;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.github.pagehelper.Page;
import com.yykj.im.center.client.form.consultation.SystemNoticeListForm;
import com.yykj.im.center.server.entity.Notice;
import com.yykj.im.center.server.exception.ErrorCode;
import com.yykj.im.center.server.exception.ErrorCodeException;
import com.yykj.im.center.server.util.LocalDateTimeUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

import java.util.List;

@Mapper
@Repository
public interface NoticeMapper extends BaseMapper<Notice> {

    default List<Notice> listNeedSend() {
        LambdaQueryWrapper<Notice> noticeLambdaQueryWrapper = new LambdaQueryWrapper<>();
        noticeLambdaQueryWrapper.eq(Notice::getDele, 0);
        noticeLambdaQueryWrapper.eq(Notice::getStatus, 0);
        noticeLambdaQueryWrapper.le(Notice::getSendTime, LocalDateTimeUtil.now());
        return this.selectList(noticeLambdaQueryWrapper);
    }

    default Page<Notice> listByCondition(SystemNoticeListForm systemNoticeListForm) {
        LambdaQueryWrapper<Notice> n = new LambdaQueryWrapper<>();
        n.eq(Notice::getDele, 0);
        if (systemNoticeListForm.getStatus() != null) {
            n.eq(Notice::getStatus, systemNoticeListForm.getStatus());
        }
        if (StringUtils.isNotBlank(systemNoticeListForm.getTitle())) {
            n.like(Notice::getTitle, systemNoticeListForm.getTitle());
        }
        if (systemNoticeListForm.getGender() != null) {
            n.eq(Notice::getGender, systemNoticeListForm.getGender());
        }
        if (systemNoticeListForm.getDepartmentId() != null) {
            n.eq(Notice::getDepartmentId, systemNoticeListForm.getDepartmentId());
        }
        if (systemNoticeListForm.getHospitalId() != null) {
            n.eq(Notice::getHospitalId, systemNoticeListForm.getHospitalId());
        }
        if (systemNoticeListForm.getStartTime() != null) {
            n.gt(Notice::getSendTime, systemNoticeListForm.getStartTime());
        }
        if (systemNoticeListForm.getEndTime() != null) {
            n.le(Notice::getSendTime, systemNoticeListForm.getEndTime());
        }
        n.orderByDesc(Notice::getCreateTime);
        return (Page) this.selectList(n);
    }

    default Notice findById(String id) {
        Notice notice = this.selectById(id);
        if (notice == null) {
            throw new ErrorCodeException(ErrorCode._9033);
        }
        return notice;
    }

    default Page<Notice> listByStatus(int status) {
        LambdaQueryWrapper<Notice> n = new LambdaQueryWrapper<>();
        n.eq(Notice::getDele, 0);
        n.eq(Notice::getStatus, status);
        n.orderByDesc(Notice::getDoSendTime);
        return (Page) this.selectList(n);
    }
}

